import { createRouter, createWebHistory } from 'vue-router'
import ChatHome from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import { authService } from '../services/authService'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: ChatHome,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫，检查需要认证的页面
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  if (requiresAuth && !authService.isAuthenticated()) {
    // 如果需要认证但未登录，跳转到登录页
    next({ name: 'Login', query: { redirect: to.fullPath } })
  } else {
    next()
  }
})

export default router